package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.graphics.Color
import android.os.Bundle
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityShedPigeonVideoBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterGetVisitVideo
import com.gexiaobao.pigeon.ui.adapter.MyAdapter
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import me.hgj.jetpackmvvm.util.startActivityForResult

/**
 * @Author      : hxw
 * @Date        : 2024/6/12 15:53
 * @Describe    : 公棚下已上传探视视频赛鸽列表
 */
class ActivityShedPigeonVideo : BaseActivity<ShedPigeonViewModel, ActivityShedPigeonVideoBinding>() {

    private var mOrgId = ""
    private var raceId = 0
    private lateinit var loadsir: LoadService<Any>
    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()
    private var mSearchType = ""
    private var ringId = ""
    private var memberName = ""
    private val mAdapter: AdapterGetVisitVideo by lazy { AdapterGetVisitVideo(arrayListOf()) }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.tvTitle.text = "探视视频"
        mSearchType = getString(R.string.search_by_foster)
        mOrgId = intent.getStringExtra("orgId").toString()
        raceId = intent.getIntExtra("raceId", 0)
        initPopup()

        //状态页配置
        loadsir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            //点击重试时触发的操作
            searchResultData(true)
        }

        eventViewModel.toRefreshData.observeInActivity(this) {
            searchResultData(true)
        }

        searchResultData(true)

        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val zItem = SwipeMenuItem(this)
                .setBackground(R.drawable.round_menu_bg5_yellow)
                .setTextColor(Color.WHITE)
                .setText("修改")
                .setTextSize(16)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(zItem)

            val pItem = SwipeMenuItem(this)
                .setBackground(R.drawable.round_menu_bg5_red)
                .setTextColor(Color.WHITE)
                .setText("删除")
                .setTextSize(16)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(pItem)
        }
        mDatabind.includeList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 左侧还是右侧菜单 */
//            val direction = menuBridge.direction
            /**  菜单在Item中的Position */
            val menuPosition = menuBridge.position
            if (menuPosition == 0) {
                startActivityForResult<ActivityUploadPigeonVideo>(
                    "raceId" to raceId,
                    "type" to 1,
                    "path" to mAdapter.data[position].path,
                    "id" to mAdapter.data[position].id,
                    "ringSn" to mAdapter.data[position].ringSn,
                    "orgId" to mOrgId,
                ) {//1-修改 2-新增
                    if (it != null && it.getBooleanExtra("isRefresh", false)) {
                        searchResultData(true)
                    }
                }
            } else {
                deleteVideoPigeon(mAdapter.data[position].id.toString())
            }
        }
        mDatabind.includeList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(Util.dp2px(this, 5f), Util.dp2px(this, 10f)))
            it.initFooter {
                //触发加载更多时请求数据
                searchResultData(false)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            searchResultData(true)
        }

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            mSearchType = mList[position]
            mDatabind.includeSearch.tvSearchType.text = mSearchType
            mList.add(0, mList.removeAt(position))
            listPopupWindow!!.dismiss()
        }

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    searchResultData(true)
                    hideSoftKeyboard(this)
                }

                else -> {}
            }
            false
        }

        mAdapter.addChildClickViewIds(R.id.llVideoPic)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.llVideoPic -> {
                    startActivity<ActivityVideoPlayer>(
                        "videoUrl" to mAdapter.data[position].path,
                        "title" to mAdapter.data[position].ringId,
                        "type" to ""
                    )
                }
            }
        }
    }

    private fun deleteVideoPigeon(id: String) {
        showLoading(getString(R.string.loading))
        mViewModel.delVisitVideo(id)
    }

    private fun onRefresh(b: Boolean) {
        if (b) {
            loadsir.showLoading()
        }
        mViewModel.getVisitVideoList(b, memberName, ringId, raceId)
    }

    override fun createObserver() {
        super.createObserver()
        /** 删除探视视频 */
        mViewModel.deleteVideoResult.observe(this) {
            RxToast.showToast("已删除")
            searchResultData(true)
        }

        /** 获取已上传探视视频的赛鸽列表 */
        mViewModel.getVisitVideoResult.observe(this) {
            loadListData(it, mAdapter, loadsir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvUploadVideoAdd,
            mDatabind.llAddPigeonVideo,
            mDatabind.includeSearch.llSearchType,
            mDatabind.includeSearch.ivClose,
            mDatabind.includeSearch.tvSearch,
            mDatabind.ivBack
        ) { it ->
            when (it) {
                mDatabind.ivBack -> {
                    finish()
                }

                mDatabind.includeSearch.tvSearch -> {
                    searchResultData(true)
                }

                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                }

                mDatabind.includeSearch.llSearchType -> {
                    listPopupWindow?.show()
                }

                mDatabind.tvUploadVideoAdd, mDatabind.llAddPigeonVideo -> {
                    startActivityForResult<ActivityUploadPigeonVideo>(
                        "raceId" to raceId,
                        "type" to 2,
                        "path" to "",
                        "id" to 0,
                        "ringSn" to "",
                        "orgId" to mOrgId,
                    ) {
                        if (it != null && it.getBooleanExtra("isRefresh", false)) {
                            searchResultData(true)
                        }
                    }
                }
            }
        }
    }

    private fun initPopup() {
        mList.add(getString(R.string.search_by_foster))
        mList.add(getString(R.string.search_by_ringId))

        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = ListPopupWindow(this)
        val adapter = MyAdapter(this, mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = mDatabind.includeSearch.llSearchType//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    private fun searchResultData(isRefresh: Boolean) {
        if (mSearchType == "搜鸽主") {
            memberName = mDatabind.includeSearch.editQuery.text.toString().trim()
            ringId = ""
        } else {
            ringId = mDatabind.includeSearch.editQuery.text.toString().trim()
            memberName = ""
        }
        onRefresh(isRefresh)
    }

}